import React from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { TouchableOpacity, View } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import BasePage from "../BasePage";
import ListEmpty from "../common/ListEmpty";
import { IconImage } from "../../utils";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import DateFilter from "../components/DateFilter";
import { inject, observer } from "mobx-react";
import moment from "moment";
import { call, setClipboardContent } from "../../utils/util";

/**
 * 异常配送列表
 */
@inject("userStore", "appStore")
@observer
export default class AbnormalDelivery extends BasePage {

  constructor(props) {
    super(props);
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: moment().format("YYYY-MM-DD"),
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData(true);
  }


  loadData(showLoading = false) {
    const {delyStartTime, delyEndTimeEnd}=this.state;
    const { userInfo,  } = this.props.userStore;
    this.isLoading = true;
    let params = {
      pageNum: this.pageNo,
      pageSize: this.pageSize,
      token:global.token,
      delivery:userInfo.name,
      startTime: `${delyStartTime} 00:00:00`,
      endTime: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
    };
    axios.get(api.getOrderDeliveryAbnormalList, {params})
      .then(res => {
        this.isLoading = false;
        this.setState({
          dataList: res.result.orderDeliveryAbnormalList,
          isRefreshing: false,
          showEmpty: IsNullOrEmpty(res.result.orderDeliveryAbnormalList),
        });
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: true,
        });
      });
  }



  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData(true);
    }
  };

  render_item = ({ item, index }) => {
    let array= item.message.split('-')
    let kfwt='',contact='',nbwt=''
    if(array)
    {
      if(array.length>0)
      {
        nbwt=array[0]
      }
      if(array.length>1)
      {
        contact=array[1]
      }
      if(array.length>2)
      {
        kfwt=array[2]
      }
    }
    return (
      <View>
        <View style={styles.titleWrap}>
          <TouchableOpacity activeOpacity={1} onPress={() => setClipboardContent(item?.xmbzNo)}>
          <Text style={commonStyles.text_black_14}>单号：{item?.xmbzNo}</Text>
          </TouchableOpacity>
          <Text style={commonStyles.text_black_14}>{moment(item?.deliveryStartTime).format('MM-DD')} {moment(item?.deliveryStartTime).format('HH:mm')}-{moment(item?.deliveryEndTime).format('HH:mm')}</Text>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>状态</Text>
            <Text style={commonStyles.text_blue_13}>{item?.orderStatusName}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>收货人</Text>
            <Text style={commonStyles.text_black_13}>{item?.receiverName}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>分仓</Text>
            <Text style={commonStyles.text_black_13}>{item?.branchWarehouse}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>联系电话</Text>
            {
              item.receiverPhone&&!item.receiverPhone.includes('*')?
                <TouchableOpacity onPress={()=>call(item?.receiverPhone,item?.ordNo)}>
                  <Text style={commonStyles.text_black_13}>{item?.receiverPhone}</Text>
                </TouchableOpacity>
                :<Text style={commonStyles.text_black_13}>{item?.receiverPhone}</Text>
            }
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>地址</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.receiverAddress}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>备注</Text>
            <Text style={commonStyles.text_black_13}>{item?.delyNeeds}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>渠道</Text>
            <Text style={commonStyles.text_black_13}>{item?.chanName}</Text>
          </View>
          <View style={{ paddingVertical: 6 }}>
            {
              item.orderDetailList && item.orderDetailList.map(data => {
                // logger("订单号", data.isScan == 0 ? data.id : "");
                return (
                  <View row marginT-5>
                    <Image source={data.isScan == 0 ? IconImage.ic_unchecked : IconImage.ic_checked}
                           style={{ width: 17, height: 17, marginRight: 5 }} />
                    <View flex>
                      <Text
                        style={commonStyles.text_black_13}>{data?.goodsName}（{data?.goodsSpecs}）(x{data?.num}）</Text>
                    </View>
                  </View>
                );
              })
            }
          </View>
        </View>
        <View style={styles.line}/>
        <View style={styles.reasonWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>客户问题</Text>
            <Text style={commonStyles.text_red_13}>{kfwt}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>内部问题</Text>
            <Text style={commonStyles.text_red_13}>{nbwt}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>是否与客户联系</Text>
            <Text style={commonStyles.text_black_13}>{contact}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>其它</Text>
            <Text style={commonStyles.text_black_13}>无</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_black_13}>处理结果</Text>
            <Text style={commonStyles.text_black_13}>{item?.reason}</Text>
          </View>
        </View>
      </View>
    );
  };

  render() {
    const { dataList, isRefreshing,} = this.state;
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"异常配送列表"}
          backgroundColor={'transparent'}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
        />
        <View style={commonStyles.container}>
          <View row centerV>
          <DateFilter  onQueryClick={(delyStartTime, delyEndTimeEnd) => this.setState({
            delyStartTime,
            delyEndTimeEnd
          }, () => this._renderRefresh(false))} />
          <TouchableOpacity activeOpacity={1} throttleTime={1000} style={styles.btn} onPress={()=>this._renderRefresh(false)}>
            <Text style={commonStyles.text_black}>刷新</Text>
          </TouchableOpacity>
        </View>
          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{ flexGrow: 1 }}
            keyExtractor={(item, index) => "menu_" + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  reasonWrap: {
    borderBottomLeftRadius: 4,
    borderBottomRightRadius: 4,
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },
  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  }
  ,line:{
    height:1,
    backgroundColor:'#EFEFEF',
    marginHorizontal:15,
  },
  btn: {
    width: 80,
    height: 40,
    ...commonStyles.center,
    backgroundColor: "#F9D63B",
    borderRadius: 5,
  },
});
